<template>
	<view class="d-kuan d-juzhong">
		<uv-overlay :show="show" @click="close">
			<view class="warp">
				<view class="rect" @tap.stop>
					<view class="title">{{ title }}</view>
					
					<view class="amount">¥{{ calculatedAmount.toFixed(2) }}</view>
					<view class="pay-type">支付方式: {{ payType === 'weixin' ? '微信支付' : '支付宝' }}</view>
					<view class="input-container">
						
						<uv-input
							v-model="inputAmount"
							type="number"
							placeholder="请输入充值金额"
							customStyle="width: 200rpx; text-align: right;"
							@dblclick="clearInputAmount"
						/>
					</view>
					<view v-if="zhifu_tishi && zhifu_tishi !== '' && erweima == ''" class="erweima" >
						<view class="pay-type-hongse">{{zhifu_tishi}}</view>
					</view>
					<view v-if="erweima && erweima !== ''" class="erweima" >
						<image :src="erweima" style="width: 210px; height: 210px;" />
						<view class="pay-type">请使用微信扫描二维码</view>
					</view>
					
					<view class="buttons">
						<uv-button type="primary" @click="handlePay" :disabled="!isAmountValid">确认充值</uv-button>
						<uv-button type="default" @click="close">取消</uv-button>
					</view>
				</view>
			</view>
		</uv-overlay>
	</view>
</template>
<script>
import { getRequest,postRequest } from '@/utils/wxRequest.js'
import Api from '@/utils/api.js'
//import duixin from '@/utils/config.js'

export default {
  name: 'Dzhifu',
  props: {
    // 控制组件显示/隐藏
    show: {
      type: Boolean,
      default: false
    },
    // 支付标题
    title: {
      type: String,
      default: '充值'
    },
    // 支付类型
    payType: {
      type: String,
      default: 'weixin'
    },
	// 充值金额
	jine: {
      type: Number,
      default: 0
    }
  },
  // 组件挂载时执行
  mounted() {
    //console.log('d-zhifu组件已挂载，jine初始值:', this.jine, '类型:', typeof this.jine);
  },
  
  watch: {
    // 监听jine属性，当jine变化时触发
    jine: {
      immediate: true, // 组件加载时立即执行一次
      handler(newVal) {
        // 无论jine的值是什么，都打印日志
        //console.log('jine的值:', newVal, '类型:', typeof newVal);
        // 由于jine属性已定义为String类型，直接转换为数字使用
        let numVal = parseFloat(newVal);
        if (numVal > 0) {
          this.inputAmount = numVal.toString();
          this.zhifu_tishi = '请充值' + numVal + '元';
        }
      }
    },
    // 监听show属性变化，当组件从隐藏变为显示时，重新根据jine设置金额
    show: {
      handler(newValue) {
        console.log('show属性变化:', newValue);
        if (newValue) {
          // 显示时根据jine值重新设置金额
          console.log('组件显示时，jine值:', this.jine, '类型:', typeof this.jine);
          let numVal = parseFloat(this.jine);
          if (numVal > 0) {
            this.inputAmount = numVal.toString();
            this.zhifu_tishi = '请充值' + numVal + '元';
          }
        }
      }
    }
  },
  data() {
    return {
      inputAmount: '', // 用户输入的金额
      queryInterval: null, // 存储支付查询轮询的定时器ID
	  erweima:'',
	  zhifu_tishi:''
    };
  },
  computed: {
	yidenglu() {
	    return (this.$store.state.memberuid && this.$store.state.keycode) ? 1 : 0;
	  },
	  keycode() {
	    return this.$store.state.keycode;
	  },
	  uid() {
	    return this.$store.state.memberuid;
	  },
	  touxiang() {
	    return this.$store.state.member? this.$store.state.member.avatar : '';
	  },
	  name1() {
		const member = this.$store.state.member;
    	if (!member) return '';
    	return member.name || member.uname || member.username || '';
	    //return this.$store.state.member? this.$store.state.member.name : '';
	  },
    // 计算实际金额
    calculatedAmount() {
      const num = Number(this.inputAmount);
      return isNaN(num) ? 0 : num;
    },
    // 验证金额是否有效
    isAmountValid() {
      return this.calculatedAmount > 0;
    }
  },
  
  methods: {
    // 关闭组件
      close() {
        // 停止支付查询轮询
        if (this.queryInterval) {
          clearInterval(this.queryInterval);
          this.queryInterval = null;
        }
		this.inputAmount = '';
        // 清除二维码数据
        this.erweima = '';
        this.$emit('close');
      },
    // 处理支付
    handlePay() {
      if (!this.isAmountValid) {
        uni.showToast({
          title: '请输入有效的充值金额',
          icon: 'none'
        });
        return;
      }
      // 触发支付事件，将支付信息传递给父组件
      this.$emit('pay', {
        amount: this.calculatedAmount,
        title: this.title,
        payType: this.payType
      });
	  //提交支付
	  this.postchongzhi_api();
      // 支付后关闭弹窗
      //this.close();
    },
    // 双击清除输入金额
    clearInputAmount() {
      this.inputAmount = '';
    },
	postchongzhi_api() {
		// 从Vuex store中获取登录会员信息
		const uid = this.$store.state.memberuid;
		const keycode = this.$store.state.keycode;
		const member = this.$store.state.member;
        
		// 检查是否已登录
		if (!uid || !keycode) {
			uni.showToast({
				icon: 'none',
				title: '请先登录',
				duration: 1000
			});
			return;
		}
		const datas = "&pay[uid]="+uid+"&pay[keycode]="+keycode+"&pay[type]="+this.payType+"&pay[money]="+this.calculatedAmount+"&pay[mark]=recharge";
		var postPayRequest = postRequest(Api.postweixin_chongzhi(uid,keycode),datas);
		postPayRequest.then(response => {
				if (response.data.code) {
					// 打印
					
					var id = response.data && response.data.data.id;
					console.log('id',response.data.data.id);
					this.getzhifu(id); // 拉起支付 第二步骤
				} else {
					this.zhifu_tishi = response.data.msg;
					uni.showToast({
						icon: 'none',
						title: response.data.msg,
						duration: 1000
					});
				}
			});

	},
	//拉起支付 第二步骤
	getzhifu(id){
		// 从Vuex store中获取登录会员信息
		const uid = this.$store.state.memberuid;
		const keycode = this.$store.state.keycode;
		// 充值订单
		var get_data = getRequest(Api.getZhifu(uid,keycode,id));
		var res;
		get_data.then(duixin_data => {
			res = duixin_data;
			if(res.data.code) {
				var erweima = res.data.data && res.data.data.code;
				this.erweima = erweima;
				// 加入支付数据库id后，读取提交的支付id
				this.getjiance_zhifu_api(id);
				
			}else{
				uni.showToast({
					icon: 'none',
					title: res.data.msg,
					duration: 1000
				});
			}
		});
	
	},
	// 微信JSAPI支付
	
	// 查询支付结果（轮询） 第三步骤
	getjiance_zhifu_api(id) {
		// 清除之前可能存在的定时器
		if (this.queryInterval) {
			clearInterval(this.queryInterval);
		}
		
		let queryCount = 0;
		const maxCount = 60; // 最多查询60次（约3分钟）
		
		this.queryInterval = setInterval(() => {
			queryCount++;
			// 调用查询支付结果的接口
			// 这里需要根据实际项目的接口进行调整
			const uid = this.$store.state.memberuid;
			const keycode = this.$store.state.keycode;
			//var get_data = getRequest(Api.getZhifu(uid,keycode,id));
			const queryUrl = Api.getZhifujiance(uid, keycode, id);
			
			getRequest(queryUrl).then(res => {
				if(res.data.code == 1) {
					// 支付成功
					clearInterval(this.queryInterval);
					this.queryInterval = null;
					uni.showToast({
						title: '支付成功',
						icon: 'success'
					});
					this.close();
					// 刷新会员信息
					// 尝试通过事件通知父组件刷新用户信息
					this.$emit('uidapi');
					
					
				} else if(queryCount >= maxCount) {
					// 查询超时
					clearInterval(this.queryInterval);
					this.queryInterval = null;
					uni.showToast({
						icon: 'none',
						title: '支付超时，请重新尝试',
						duration: 1500
					});
				}
			});
		}, 3000); // 每3秒查询一次
	}

  }
}
</script>

<style>
    .warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.rect {
		width: 500rpx;
		background-color: #fff;
		border-radius: 10rpx;
		padding: 40rpx;
		box-sizing: border-box;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.input-container {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 30rpx;
		font-size: 28rpx;
	}

	.input-container text {
		margin-right: 10rpx;
	}

	.amount {
		font-size: 48rpx;
		color: #e64340;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.pay-type {
		font-size: 28rpx;
		color: #666;
		text-align: center;
		margin-bottom: 40rpx;
	}
	.pay-type-hongse {
		font-size: 28rpx;
		color: #fd5d5d;
		text-align: center;
		margin-bottom: 40rpx;
	}

	.buttons {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	uv-button {
		width: 100%;
	}
</style>